package flatui

import (
	"encoding/json"
	"git.oschina.net/liukexing/RbacManager/models/center"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/context"
	"github.com/astaxie/beego/httplib"
	"github.com/astaxie/beego/orm"
	"strconv"
)

type UA struct {
	Agent_type        string
	Agent_name        string
	Agent_version     string
	Os_type           string
	Os_name           string
	Os_versionName    string
	Os_producer       string
	Os_producerURL    string
	Linux_distibution string
	Agent_language    string
	Agent_languageTag string
}

//Syncdb
func Syncdb() {
	name := "default" // 数据库别名
	force := false    // drop table 后再建表
	verbose := true   // 打印执行过程
	err := orm.RunSyncdb(name, force, verbose)
	if err != nil {
		beego.Error(err)
	}
}

func UpdateAgent(agent string) (json string, err error) {
	json, err = center.FindUcAgent(agent)
	if err != nil {
		err = nil
		req := httplib.Get("http://www.useragentstring.com/")
		req.Param("uas", agent)
		req.Param("getJSON", "all")
		json, err := req.String()
		if err == nil {
			center.AddUcAgent(agent, json)
		}
	} else {
		center.IncUcAgent(agent)
	}
	return
}

var GetUserAgent = func(ctx *context.Context) {
	CruSession := ctx.Input.CruSession
	v := CruSession.Get("user-agent")
	User_agent := CruSession.Get("ua")
	if v == nil || User_agent == nil {
		CruSession.Set("user-agent", ctx.Request.UserAgent())
		var agent UA
		str, err := UpdateAgent(ctx.Request.UserAgent())
		if err == nil {
			if err := json.Unmarshal([]byte(str), &agent); err == nil {
				CruSession.Set("ua", agent)
				i, _ := strconv.ParseFloat(agent.Agent_version, 32)
				CruSession.Set("respond", (agent.Agent_name == "Internet Explorer" && i < 9))
			} else {
				beego.Debug("Unmarshal:", err)
			}
		} else {
			beego.Debug("UpdateAgent:", err)
		}
	} else {
		if v != ctx.Request.UserAgent() {
			CruSession.Flush()
		}
	}
}
